// 统一处理模糊查询语句
const { Op } = require("sequelize");
export const whereParamasHandler = (
  data: Record<string, any>, // 搜索字段
  pageData?: Record<string, any> | null, // 分页 排序
  like: boolean = true // 是否模糊查询
): Record<string, any> => {
  const whereValue = Object.keys(data).reduce((pre, cur) => {
    if (data[cur] !== undefined && !!data[cur]) {
      pre[cur] = like
        ? {
            [Op.like]: `%${data[cur]}%`,
          }
        : data[cur];
    }
    return pre;
  }, {} as Record<string, any>);
  if (pageData) {
    // 转换页码和每页大小为数字类型
    const pageNumber = parseInt(pageData.page as string, 10) || 1;
    const pageSizeNumber = parseInt(pageData.pageSize as string, 10) || 10;
    const offset = (pageNumber - 1) * pageSizeNumber; // 计算偏移量
    const limit = pageSizeNumber; // 每页记录数
    return {
      where: whereValue,
      offset,
      limit,
      order: [
        [pageData?.sortField ?? "createdAt", pageData?.sortOrder ?? "DESC"],
      ],
    };
  } else {
    return {
      where: whereValue,
    };
  }
};
